﻿using System;
using System.IO;
using System.Net;
using cloud_store_rest_api;

namespace cloud_store_rest_api_dotnet4
{
    public class dotnet4WebClient : IWebClient
    {
        private readonly WebClient _webClient = new WebClient();
        private Action<string> _callbackDownloadStringCompleted;
        private Action<Stream> _callbackOpenReadCompleted;

        public dotnet4WebClient()
        {
            _webClient.DownloadStringCompleted += _webClient_DownloadStringCompleted;
            _webClient.OpenReadCompleted += _webClient_OpenReadCompleted;
        }

// ReSharper disable InconsistentNaming
        void _webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
// ReSharper restore InconsistentNaming
        {
            if (_callbackOpenReadCompleted == null)
                return;

            _callbackOpenReadCompleted(e.Result);

            _callbackOpenReadCompleted = null;
        }

// ReSharper disable InconsistentNaming
        void _webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
// ReSharper restore InconsistentNaming
        {
            if (_callbackDownloadStringCompleted == null)
                return;

            _callbackDownloadStringCompleted(e.Result);

            _callbackDownloadStringCompleted = null;
        }

        public void DownloadStringAsync(Uri uri, Action<string> callback)
        {
            _callbackDownloadStringCompleted = callback;

            _webClient.DownloadStringAsync(uri);
        }

        public void OpenReadAsync(Uri uri, Action<Stream> callback)
        {
            _callbackOpenReadCompleted = callback;

            _webClient.OpenReadAsync(uri);
        }
    }
}
